<?php
namespace app\api\service;
use think\facade\Cache;
use think\facade\Log;
use GuzzleHttp\Client;
class VpayService {

    public function createOrder($tradeNo, $amount, $payType){
        $data = [
            'trade_no' => $tradeNo,
            'amount' => $amount,
            'type' => $payType,
        ];
        return $this->send('/api/app/createOrder',$data);
    }

    public function closeOrder($tradeNo){
        if(empty($tradeNo)){
            return;
        }
       return $this->send('/api/app/closeOrder',[
            'trade_no' => $tradeNo,
        ]);
    }

    public function queryAvailableClient(){
        return $this->send('/api/app/queryAvailableClient',[] ,'GET');
    }


    
    public function send($url, $data, $method = 'POST'){
        $config = config('vpay');
        $client = new Client(['base_uri' => $config['base_url']]);
        $data = array_merge([
            'appid' => $config['appid'],
            't' => time(),
        ], $data);
        $data['sign'] = $this->sign($data, $config['appsecret']);

        if(strtoupper($method) == 'POST'){
            $response = $client->post($url, [
                'form_params' => $data
            ]);
        }else{
            $response = $client->get($url, [
                'query' => $data
            ]);
        }
      
        if($response->getStatusCode()!= 200){
            throw new \Exception('网络错误');
        }
        $result = json_decode( $response->getBody()->getContents(), true);
        if($result['code'] != 1){
            return  throw new \Exception($result['msg']);
        }
        return $result['data'];
    }

    private function sign($data, $key) {
        ksort($data);
        $signStr = '';
        $signStr = implode('&', array_map(function($k, $v) {
            return $k . '=' . $v;
        }, array_keys($data), $data));
        $signStr .=  $key;
  
        return md5($signStr);
    }
    
    public function checkSign($data){
        $config = config('vpay');
        $sign = $data['sign'];
        unset($data['sign']);
        $signStr = $this->sign($data, $config['appsecret']);
        if($signStr != $sign){
            throw new \Exception('签名错误');
        }
    }
}